<template>
	<!-- 添加供应商 -->
	<div class="article-manager video-icon form-submit" id="shopp-manager">
		<div class="i-layout-page-header">
			<PageHeader class="product_tabs" hidden-breadcrumb>
				<div slot="title" class="acea-row row-middle">
					<router-link :to="{ path: `${roterPre}/supplier/menu/list` }">
						<div class="font-sm after-line">
							<span class="iconfont iconfanhui"></span>
							<span class="pl10">返回</span>
						</div>
					</router-link>
					<span v-text="$route.params.id ? '编辑供应商' : '添加供应商'" class="mr20 ml16"></span>
				</div>
			</PageHeader>
		</div>
		<Card :bordered="false" dis-hover class="ivu-mt">
			<Form class="formValidate mt20" ref="formValidate" :rules="ruleValidate" :model="formValidate"
				:label-width="width" :label-position="labelPosition" @submit.native.prevent>
				<Row :gutter="24" type="flex">
					<Col span="24">
					<FormItem label="供应商代码：" prop="code">
						<Input maxlength="20" show-word-limit v-model="formValidate.code" disabled placeholder="自动生成"
							v-width="460" />
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="供应商名称：" prop="supplier_name">
						<Input maxlength="50" show-word-limit v-model="formValidate.supplier_name"
							placeholder="请输入供应商名称" v-width="460" />
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="英文名称：" prop="en_name">
						<Input maxlength="50" show-word-limit v-model="formValidate.en_name" placeholder="请输入英文名称"
							v-width="460" />
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="账号类型：" prop="house_type">
						<Select v-model="formValidate.type" v-width="460">
							<Option :value="1">A类账户</Option>
							<Option :value="2">B类账户</Option>
						</Select>
					</FormItem>
					</Col>

					<!-- <Row :gutter="24" type="flex"> -->
					<Col span="24">
					<FormItem label="联系人姓名：" prop="name">
						<Input maxlength="20" show-word-limit v-model="formValidate.name" placeholder="请输入联系人姓名"
							v-width="460" />
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="whatsapp：" prop="name">
						<Input maxlength="20" show-word-limit v-model="formValidate.whatsapp" placeholder="请输入whatsapp"
							v-width="460" />
					</FormItem>
					</Col>
					<!-- </Row> -->

					<Col span="24">
					<FormItem label="联系电话：" prop="phone">
						<Input maxlength="11" show-word-limit v-model="formValidate.phone" placeholder="请输入联系电话"
							v-width="460" />
					</FormItem>
					</Col>

					<!-- <Col span="24">
					<FormItem label="主营产品：" prop="sales_type">
						<Input maxlength="20" show-word-limit v-model="formValidate.sales_type" placeholder="请输入主营产品"
							v-width="460" />
					</FormItem>
					</Col> -->

					<!-- 产品区域 -->
					<Col span="24">
					<FormItem label="主营产品：" prop="">
					  <Col span="24">
					    <FormItem v-if="formValidate.product_data.length !== 0">
					      <div class="dragArea list-group"
					           :list="formValidate.product_data"
					           group="peoples"
					           handle=".move-icon"
					           :move="checkMove"
					           @end="end">
					        <div v-for="(item, index) in formValidate.product_data"
					             :key="index"
					             class="acea-row row-middle mb10">
					          <div style="width: 90%"
					               :class="moveIndex === index ? 'borderStyle' : ''">
					            <div class="acea-row row-middle">
					              <!-- 名称下拉框 -->
					              <Select
					                :value="item.name"
					                filterable
					                v-width="'25%'"
					                :label-in-value="true"
					                @on-change="(val) => handleSelectChange(val, index)"
					              >
					                <Option v-for="opt in cityList" :value="opt.value" :key="opt.value">{{ opt.label }}</Option>
					              </Select>
					
					              <!-- 值输入框 -->
					              <Input v-model="item.value" class="mr5" v-width="'25%'" />
					
					              <!-- 删除按钮 -->
					              <Icon type="ios-close-circle"
					                    size="14"
					                    class="curs"
					                    @click="removeAttrData(index)" />
					            </div>
					          </div>
					        </div>
					      </div>
					    </FormItem>
					  </Col>
					</FormItem>
					</Col>
					<Col span="24" v-if="createShuxin">
					<FormItem>
						<Button type="primary" icon="md-add" @click="addShuXinBtn" class="mr15">添加新主营产品</Button>
					</FormItem>
					</Col>
					</Col>


					<Col span="24">
					<FormItem label="国家地址" prop="addressSelect">
						<Cascader :data="addresData" v-model="formValidate.addressSelect" @on-change="addchack"
							change-on-select v-width="460" filterable></Cascader>
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="供应商地址：" prop="address">
						<Input maxlength="50" show-word-limit v-model="formValidate.address" placeholder="请输入供应商地址"
							v-width="460" />
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="供应商邮箱：" prop="email">
						<Input maxlength="50" show-word-limit v-model="formValidate.email" placeholder="请输入供应商邮箱"
							v-width="460" />
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="佣金类型：" prop="house_type">
						<Select v-model="formValidate.house_type" v-width="460">
							<Option :value="1">5%佣金</Option>
							<Option :value="2">10%佣金</Option>
						</Select>
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="仓储类型：" prop="warehouse_type">
						<Select v-model="formValidate.warehouse_type" v-width="460">
							<Option :value="0">标准版</Option>
							<Option :value="1">30天免仓版</Option>
						</Select>
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="出库费用/单：" prop="freight_price">
						<InputNumber v-model="formValidate.freight_price" maxlength="3" show-word-limit :max="100"
							:min="1" v-width="460" />
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="备注：" prop="mark">
						<Input maxlength="500" show-word-limit type="textarea" v-model="formValidate.mark"
							placeholder="请输入..." v-width="460" />
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="供应商登录用户名：" prop="account">
						<Input maxlength="20" show-word-limit v-model="formValidate.account" disabled placeholder="自动生成"
							v-width="460" />
					</FormItem>
					</Col>

					<Col span="24">
					<FormItem label="排序：">
						<InputNumber v-width="460" :min="0" :max="999999" v-model="formValidate.sort"
							placeholder="请输入排序" />
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="是否开启：">
						<i-switch v-model="formValidate.is_show" :true-value="1" :false-value="0" size="large">
							<span slot="open">开启</span>
							<span slot="close">关闭</span>
						</i-switch>
					</FormItem>
					</Col>
				</Row>
			</Form>
		</Card>
		<Card :bordered="false" dis-hover class="fixed-card"
			:style="{ left: `${!menuCollapse ? '200px' : isMobile ? '0' : '80px'}` }">
			<Form>
				<FormItem>
					<Button type="primary" class="submission" @click="handleSubmit('formValidate')">保存</Button>
				</FormItem>
			</Form>
		</Card>
	</div>
</template>
<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		getSupplier,
		addSupplier,
		putSupplier,
		getCustomerInformation
	} from '@/api/supplier'
	import {
		cityApi,
		areaInfoApi,
		allAreaInfoApi
	} from '@/api/store'
	import Setting from "@/setting";
	import {
		cacheDelete,
		productAddApi
	} from "@api/product";
	export default {
		name: '',
		components: {},
		props: {},
		data() {
			return {
				roterPre: Setting.roterPre,
				cityList: [{
						value: 1,
						label: '卧室'
					},
					{
						value: 2,
						label: '客厅'
					},
          {
            value: 3,
            label: '餐厅'
          },
          {
            value: 4,
            label: '室内软装'
          }
				],
				width: 150,
				addresData: [],
				addressSelect1: [],
				moveIndex: "",
				createShuxin: true,
				formValidate: {
					code: '',
					type:1,
					supplier_name: '',
					en_name:"",
					name: '',
					phone: '',
					detailed_address: '',
					whatsapp:'',
					address: '',
					addressSelect: [],
					product_data: [{
						label: '',
						name: '',
						value: ''
					}],
					email: '',
					mark: '',
					account: '',
					pwd: '',
					conf_pwd: '',
					is_show: 0,
					province: 0,
					city: 0,
					area: 0,
					street: 0,
					warehouse_type: '',
					house_type: '',
					freight_price: 0,
				},
				ruleValidate: {
					// code: [{
					// 	required: true,
					// 	message: '供应商代码不能为空',
					// 	trigger: 'blur'
					// }, ],
					supplier_name: [{
						required: true,
						message: '供应商不能为空',
						trigger: 'blur',
					}, ],
					phone: [{
							required: true,
							message: '联系电话不能为空',
							trigger: 'blur'
						},
						{
							pattern: /^1[3456789]\d{9}$/,
							message: '手机号码格式不正确',
							trigger: 'blur',
						},
					],
					// account: [{
					// 	required: true,
					// 	message: '请输入用户名',
					// 	trigger: 'blur',
					// }, ],
					email: [{
						required: true,
						message: '请输入邮箱',
						trigger: 'blur',
					}, ],
					address: [{
						required: true,
						message: '请填写具体地址',
						trigger: 'change',
					}, ],
					addressSelect: [{
							required: true,
							message: '请选择省市区',
							type: 'array',
							min: 1,
							trigger: 'change'
						},
						{
							type: 'array',
							max: 4,
							message: '格式不合法',
							trigger: 'change'
						}

					],
					house_type: [{
						required: true,
						type: 'number',
						message: '佣金类型必填',
						trigger: 'change'
					}, ],
					warehouse_type: [{
						required: true,
						type: 'number',
						message: '仓储类型必填',
						trigger: 'change'
					}, ],
					freight_price: [{
						required: true,
						type: 'number',
						message: '出库费用必填',
						trigger: 'blur'
					}, ],
				},
			}
		},
		computed: {
			...mapState('admin/layout', ['isMobile', 'menuCollapse']),
			labelPosition() {
				return this.isMobile ? 'top' : 'right'
			},
		},
		watch: {},
		created() {
			let data = {
				pid: 0,
				id: 1
			}
			this.cityInfo(data)
			if (this.$route.params.id) {
				this.getSupplier()
			}
		},
		mounted() {},
		methods: {
			// handleSelectChange(val, index) {
			// 	// 更新当前项的label
			// 	this.formValidate.product_data[index].label = val.label;
			// },
			handleSelectChange(val, index) {
			  // val = { value: 1, label: '卧室' }
			  this.formValidate.product_data[index].name = val.value;
			  this.formValidate.product_data[index].label = val.label;
			},
			end() {
				this.moveIndex = "";
			},
			checkMove(evt) {
				this.moveIndex = evt.draggedContext.index;
			},
			addShuXinBtn() {
				this.formValidate.product_data.push({
					name: '',
					value: '',
					label:'',
				});
			},
			removeAttrData(index) {
				this.formValidate.product_data.splice(index, 1);
			},
			// 获取省市区
			// cityInfo(data) {
			// 	cityApi(data).then((res) => {
			// 		this.addresData = res.data
			// 	})
			// },
			// loadData(item, callback) {
			// 	item.loading = true
			// 	cityApi({
			// 		pid: item.value
			// 	}).then((res) => {
			// 		item.children = res.data
			// 		item.loading = false
			// 		callback()
			// 	})
			// },
			// 获取省市区
			cityInfo(data) {
				allAreaInfoApi(data).then((res) => {
					this.addresData = res.data
				})
				// areaInfoApi(data).then((res) => {
				//   this.addresData = res.data
				// })
			},
			// loadData(item, callback) {
			//   item.loading = true
			//   areaInfoApi({ pid: item.value }).then((res) => {
			//     item.children = res.data
			//     item.loading = false
			//     callback()
			//   })
			// },
			// 选择省市区
			addchack(e, selectedData) {
				e.forEach((i, index) => {
					if (index == 0) {
						this.formValidate.province = i
					} else if (index == 1) {
						this.formValidate.city = i
					} else if (index == 2) {
						this.formValidate.area = i
					} else {
						this.formValidate.street = i
					}
				})
				let addressInfo = [];
				selectedData.forEach(item => {
					addressInfo.push(item.label)
				})
				this.formValidate.address = addressInfo.join('');
			},
			// 添加供应商
			handleSubmit(name) {
				console.log("product_data", this.formValidate.product_data)
				if (this.$route.params.id && this.$route.query.type != 1) {
					this.$refs[name].validate((valid) => {
						if (valid) {
							putSupplier(this.$route.params.id, this.formValidate)
								.then(async (res) => {
									this.$Message.success(res.msg)
									this.$router.push({
										path: this.roterPre + '/supplier/menu/list'
									})
								}).catch((res) => {
									this.$Message.error(res.msg)
								})
						} else {
							return this.$Message.warning("信息校验不通过");
						}
					});
					
				} else {
					this.$refs[name].validate((valid) => {
						if (valid) {
							addSupplier(this.formValidate)
								.then(async (res) => {
									this.$Message.success(res.msg)
									this.$router.push({
										path: this.roterPre + '/supplier/menu/list'
									})
								})
								.catch((res) => {
									this.$Message.error(res.msg)
								})
						} else {
							return this.$Message.warning("信息校验不通过");
						}
					});
				}
			},
			// 获取供应商信息
			getSupplier() {
				if (this.$route.query.type == 1) {
					//一键开户
					getCustomerInformation(this.$route.params.id)
						.then(async (res) => {
							// this.formValidate = res.data.info
							let info = res.data.info
							let addressSelect = []
							if (res.data.info.province) {
								addressSelect.push(res.data.info.province)
							}
							if (res.data.info.city) {
								addressSelect.push(res.data.info.city)
							}
							if (res.data.info.area) {
								addressSelect.push(res.data.info.area)
							}
							if (res.data.info.street) {
								addressSelect.push(res.data.info.street)
							}
							this.formValidate.addressSelect = addressSelect
							this.formValidate.supplier_name = info.company_name
							this.formValidate.en_name = info.company_name_en
							this.formValidate.name = info.contacts
							this.formValidate.phone = info.phone
							this.formValidate.email = info.email
						})
						.catch((res) => {
							this.$Message.error(res.msg)
						})
				} else {
					getSupplier(this.$route.params.id)
						.then(async (res) => {
							this.formValidate = res.data
							let addressSelect = []
							if (res.data.province) {
								addressSelect.push(res.data.province)
							}
							if (res.data.city) {
								addressSelect.push(res.data.city)
							}
							if (res.data.area) {
								addressSelect.push(res.data.area)
							}
							if (res.data.street) {
								addressSelect.push(res.data.street)
							}
							this.formValidate.addressSelect = addressSelect
						})
						.catch((res) => {
							this.$Message.error(res.msg)
						})
				}
			},
		},
	}
</script>
<style scoped lang="less">
	.fixed-card {
		position: fixed;
		right: 0;
		bottom: 0;
		left: 200px;
		z-index: 99;
		box-shadow: 0 -1px 2px rgb(240, 240, 240);
	}

	.submission {
		margin-left: 50%;
	}

	.borderStyle {
		border: 1px solid #ccc;
		padding: 8px;
		border-radius: 4px;
	}
</style>